<template>
  <el-dialog :title="disabled ? $t('table.preview') : id?$t('table.edit'):$t('table.add')" @close="onClose" :visible.sync="_visible">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="temp"
      label-position="left"
      label-width="70px"
      style="width: 400px; margin-left:50px;"
      v-loading="loading"
      :disabled="disabled"
    >
      <el-form-item :label="$t('table.avatarFileId')" prop="avatarFileId">
        <el-upload
          :action="uploadUrl"
          :headers="{
            'authorization': token
          }"
          list-type="picture-card"
          :show-file-list="false"
          accept=".mp4,"
          :on-success="onUploadSuccess"
          :on-error="onUploadError"
        >
          <img v-if="file" :src="file.url">
          <i v-else class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item :label="$t('table.status')" prop="status">
        <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
          <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" v-if="!disabled">
      <el-button @click="handleClose">
        {{ $t('table.cancel') }}
      </el-button>
      <el-button type="primary" @click="id ? updateData() : createData()">
        {{ $t('table.confirm') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getUserById, updateUser, addUser } from '@/api/manageUser'
import { getToken } from '@/utils/auth'
import i18n from '@/lang'
const statusOptions = [
  { key: 'enabled', display_name: i18n.t('table.enabled') },
  { key: 'disabled', display_name: i18n.t('table.disabled') }
]

export default {
  name: '',
  props: {
    visible: Boolean,
    id: [Number, String],
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      token: getToken(),
      uploadUrl: process.env.VUE_APP_BASE_API + '/video',
      temp: {
        id: undefined,
        status: 'enabled',
        avatarFileId: undefined
      },
      rules: {
        status: [{ required: true, message: 'type is required', trigger: 'change' }],
        avatarFileId: [{ required: true, message: 'image is required', trigger: 'blur' }]
      },
      file: null,
      editPassword: false,
      statusOptions,
      loading: false
    }
  },
  computed: {
    _visible: {
      get(){ return this.visible },
      set(val){ this.$emit('update:visible', val) }
    }
  },
  watch: {
    visible(newV){
      if(newV && this.id){
        this.getUserData(this.id)
      }
    }
  },
  methods: {
    getUserData(id){
      this.loading = true
      getUserById(id).then(({data}) => {
        this.loading = false
        data.avatarFileId = data.avatarFile?.id
        console.log(data, 'getUserData')
        this.temp = Object.assign({}, data)
        this.file = data.avatarFile
      }).catch((err) => {
        console.log(err, 'getUserData')
        this.loading = false
      })
    },
    resetTemp() {
      this.file = null
      this.temp = {
        id: undefined,
        name: '',
        status: 'enabled',
        avatarFileId: undefined
      }
    },
    onUploadSuccess(e) {
      if (e?.code === 200) {
        this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this._visible = false
            this.$emit('refresh')
      } else {
        this.$message.error(e.msg)
      }
    },
    onUploadError(e) {
      this.$message.error(e.msg || 'faild')
    },
    handleClose(){
      this._visible = false
    },
    onClose(){
      console.log('onClose')
      this.resetTemp()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.temp))
          if(!this.editPassword){
            delete data.password
          }
          updateUser(data).then(res => {
            this._visible = false
            this.$emit('refresh')
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addUser(this.temp).then(res => {
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this._visible = false
            this.$emit('refresh')
          })
        }
      })
    },
  }
}
</script>

<style lang="scss">
</style>
